package com.example.hanfu.login;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class LoginDBManager {
    private LoginDBHelper dbHelper;
    private String TBNAME;
    private static final String TAG = "DBTikuManager";
    public LoginDBManager(Context context) {
        dbHelper = new LoginDBHelper(context);
        TBNAME = LoginDBHelper.TB_NAME;
    }

    public void deleteAll(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(TBNAME,null,null);
        db.close();
    }

    public void delete(String id){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(TBNAME, "id=?", new String[]{String.valueOf(id)});
        db.close();
    }
    public void add(Login item){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("id", item.getId());
        values.put("pwd",item.getPwd());
        db.insert(TBNAME, null, values);
        db.close();
    }
    public Login findById(String id){
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(TBNAME, null, "id=?", new String[]{id}, null, null, null);
        Login item = null;
        if(cursor!=null && cursor.moveToFirst()){
            item = new Login();
            item.setId(cursor.getString(cursor.getColumnIndex("id")));
            item.setPwd(cursor.getString(cursor.getColumnIndex("pwd")));
            cursor.close();
        }
        db.close();
        return item;
    }


    public List<Login> listAll(){
        List<Login> list = null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(TBNAME, null, null, null, null, null, null);
        if(cursor!=null){
            list = new ArrayList<Login>();
            while(cursor.moveToNext()){
                Login item = new Login();
                item.setId(cursor.getString(cursor.getColumnIndex("id")));
                item.setPwd(cursor.getString(cursor.getColumnIndex("pwd")));
                list.add(item);
            }
            cursor.close();
        }
        db.close();
        return list;

    }
}
